package com.prs.crm.action.stock;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.prs.crm.action.FlowAction;
import com.prs.crm.annotation.Clew;
import com.prs.crm.annotation.FlowActive;
import com.prs.crm.annotation.FlowStart;
import com.prs.crm.context.AppContext;
import com.prs.crm.domain.Currency;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.purchase.PurchaseOrder;
import com.prs.crm.domain.purchase.PurchaseOrderDetail;
import com.prs.crm.domain.stock.Product;
import com.prs.crm.domain.stock.Purchase;
import com.prs.crm.domain.stock.PurchaseDetail;
import com.prs.crm.domain.stock.PurchaseType;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeInvoice;
import com.prs.crm.service.CurrencyService;
import com.prs.crm.service.stock.PurchaseService;
import com.prs.crm.service.stock.PurchaseTypeService;
import com.prs.crm.service.sys.CodeInvoiceService;
import com.prs.crm.service.sys.CodeService;

public class PurchaseAction extends FlowAction<Purchase> {

	private static final long serialVersionUID = 1L;
	
	private String Encode;
	private CodeInvoice codeInvoice;
	private CodeInvoiceService codeInvoiceService;
	private Code code;
	private CodeService codeService;
	private Collection<CodeInvoice> codelist;
	private Purchase purchase;
	private String joiners;
	private Product[] products;
	private Double[] prices;
	private Integer[] stockNumes;
	private Integer[] storedNums;
	private Double[] discounts;
	private Double[] total;
	private Collection<PurchaseDetail> slist;
	@Autowired
	private PurchaseService purchaseService;
	@Autowired
	private CurrencyService currencyService;
	private PurchaseTypeService purchaseTypeService;
	private PaginationSupport pagination;
	private List<Currency> currencys;
	private List<PurchaseType> purchasetypes;
	private PurchaseOrder purchaseOrder;
	private List<PurchaseOrderDetail> states;	
	private String flow;
	private File upload;
	private String uploadFileName;
	
	

	
	
	
	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public List<PurchaseOrderDetail> getStates() {
		return states;
	}

	public void setStates(List<PurchaseOrderDetail> states) {
		this.states = states;
	}

	public Integer[] getStoredNums() {
		return storedNums;
	}

	public void setStoredNums(Integer[] storedNums) {
		this.storedNums = storedNums;
	}

	

	public String getJoiners() {
		return joiners;
	}

	public void setJoiners(String joiners) {
		this.joiners = joiners;
	}

	public List<Currency> getCurrencys() {
		return currencys;
	}

	public void setCurrencys(List<Currency> currencys) {
		this.currencys = currencys;
	}

	public Purchase getPurchase() {
		return purchase;
	}

	public void setPurchase(Purchase purchase) {
		this.purchase = purchase;
	}

	public PurchaseService getPurchaseService() {
		return purchaseService;
	}

	public void setPurchaseService(PurchaseService purchaseService) {
		this.purchaseService = purchaseService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public CurrencyService getCurrencyService() {
		return currencyService;
	}

	public void setCurrencyService(CurrencyService currencyService) {
		this.currencyService = currencyService;
	}

	public PurchaseTypeService getPurchaseTypeService() {
		return purchaseTypeService;
	}

	public void setPurchaseTypeService(PurchaseTypeService purchaseTypeService) {
		this.purchaseTypeService = purchaseTypeService;
	}

	public List<PurchaseType> getPurchasetypes() {
		return purchasetypes;
	}

	public void setPurchasetypes(List<PurchaseType> purchasetypes) {
		this.purchasetypes = purchasetypes;
	}

	public Product[] getProducts() {
		return products;
	}

	public void setProducts(Product[] products) {
		this.products = products;
	}

	public Double[] getPrices() {
		return prices;
	}

	public void setPrices(Double[] prices) {
		this.prices = prices;
	}

	public Integer[] getStockNumes() {
		return stockNumes;
	}

	public void setStockNumes(Integer[] stockNumes) {
		this.stockNumes = stockNumes;
	}

	public Double[] getDiscounts() {
		return discounts;
	}

	public void setDiscounts(Double[] discounts) {
		this.discounts = discounts;
	}

	public Double[] getTotal() {
		return total;
	}

	public void setTotal(Double[] total) {
		this.total = total;
	}

	public Collection<PurchaseDetail> getSlist() {
		return slist;
	}

	public void setSlist(Collection<PurchaseDetail> slist) {
		this.slist = slist;
	}

	public PurchaseOrder getPurchaseOrder() {
		return purchaseOrder;
	}

	public void setPurchaseOrder(PurchaseOrder purchaseOrder) {
		this.purchaseOrder = purchaseOrder;
	}

	@FlowActive(target = "purchase", flowservice = "purchaseService")
	@Action("editPurchase")
	public String editpurchase() {
		this.currencys = this.getCurrencyService().getAllCurrency();
		this.purchasetypes = this.getPurchaseTypeService().getAllTypes();
		this.codelist = this.getCodeInvoiceService().getInvoiceCodeType("采购单");
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@FlowStart(flowservice = "purchaseService", target = "purchase")
	// 启动流程
	@Action(value = "savePurchase", results = {
			@Result(name = "success", type = "redirect", location = "listPurchase"),
			@Result(name = "error", type = "chain", location = "editPurchase"),
			@Result(name = "none", type = "redirect", location = "listPurchase") })
	public String savePurchase() {
		if ("n".equals(Encode)) {
			int EncodeRplice = this.getCodeService().getBackRpliceAll("手动编码",
					"采购单",purchase.getPurchaseCode());
			if (EncodeRplice != 0) {
				this.addActionError("编码重复!请重新输入");
				return ERROR;
			}
		}
		
		
		if(flow==null||flow.equals("")) {
			this.addActionError("流程不能为空");
			return ERROR;
		}
		if(purchase.getName()==null||purchase.getName().equals("")){
			
			this.addActionError("主题不能为空");
			return ERROR;
		}
		if(purchase.getPurchaseCode()==null||purchase.getPurchaseCode().equals("")){
			this.addActionError("编号不能为空");
			return ERROR;
		}
		if(purchase.getPurchaseDate()==null){
			this.addActionError("时间不能为空");
			return ERROR;
		}
		if(joiners==null){
			this.addActionError("参与人不能为空");
			return ERROR;
		}
		if(products==null){
			this.addActionError("商品不能为空");
			return ERROR;
		}
		purchase.setPrincipal(AppContext.getAccountContext().currentUser());
	
		

		/**
		 * 编码产生
		 */
		if ("n".equals(Encode)) {
			Code codes = new Code();
			codes.setCodeValue(purchase.getPurchaseCode());
			codes.setCodeMolde("采购单");
			codes.setEntityName(this.getClass().getName());
			codes.setCodeType("手动编码");
			this.getCodeService().save(codes);
			purchase.setCode(codes);
			this.getPurchaseService().savePurchase(purchase, products, joiners, stockNumes,upload,uploadFileName);
		} else {
			CodeInvoice Vob = this.getCodeInvoiceService().getVobject(
					codeInvoice.getId());
			Code codes = new Code();
			codes.setCodeMolde("采购单");
			codes.setEntityName(this.getClass().getName());
			codes.setCodeValue(purchase.getPurchaseCode());
			Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
			this.getCodeInvoiceService().saveOrUpdate(Vob);
			codes.setCodeType(Vob.getCodePlan());
			this.getCodeService().save(codes);
			purchase.setCode(codes);
			this.getPurchaseService().savePurchase(purchase, products, joiners, stockNumes,upload,uploadFileName);
		}


		
		this.setPrompt("操作成功");
		return SUCCESS;
	}

	@Action("listPurchase")
	public String execute() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Purchase.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getPurchaseService().listByPage(criteria,pagination));
		return SUCCESS;
	}

	@Action("viewPurchase")
	public String viewPurcahse() {
		purchase = this.getPurchaseService().get(purchase.getId());
		this.slist = purchase.getDetails();
		Iterator<Person> iter = purchase.getJoiners().iterator();
		joiners = "";
		while (iter.hasNext()) {
			joiners += iter.next().getResume().getName() + " , ";
		}
		this.displayEndNodes(purchase);
		return SUCCESS;
	}

	@Action("viewCritiquePurcahse")
	public String viewCritiquePurchase() {
		return SUCCESS;
	}

	@Action("selectPurchase")
	public String selectpurchase() {
		
		int valu = 2;
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(PurchaseOrder.class);
		criteria.add(Restrictions.eq("flowstatus", valu));
		criteria.add(Restrictions.eq("purStoreState", 0));
		criteria.add(Restrictions.eq("flowstatus", 2)); 
		this.setPagination(this.getPurchaseService().listByPage(criteria,
				getPaginationHelper().prepare(pagination)));
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	@Action(value = "importPurchase", results = { @Result(name = "success", type = "json", params = {
			"root", "states" }) })
	public String saveinportpurchase() {
		states = new ArrayList<PurchaseOrderDetail>();
		//purchase = this.getPurchaseService().get(purchase.getId());
		List alist1 = new ArrayList();
		List alist2 = new ArrayList();
		List alist3 = new ArrayList();
		List alist4 = new ArrayList();	
		List alist5 = new ArrayList();	
		for(PurchaseOrderDetail detail:purchaseOrder.getDetails()){
			if(detail.getStockNum()>detail.getInNum()){
				alist1.add(detail.getId());
				alist2.add(detail.getProducName());
				alist3.add(detail.getStockNum()-detail.getInNum());
				alist5.add(detail.getProduct().getId());
			}
		}
//		Iterator<PurchaseOrderDetail> it=purchaseOrder.getDetails().iterator();
//		Iterator<PurchaseOrderDetail> it1=purchaseOrder.getDetails().iterator();
//		Iterator<PurchaseOrderDetail> it2=purchaseOrder.getDetails().iterator();
//		while(it1.hasNext()){
//			 alist1.add(it1.next().getId());	
//		}
//		while(it.hasNext()){
//			 alist2.add(it.next().getProduct().getName());	
//		}
//		while(it2.hasNext()){
//				 alist3.add(it2.next().getStockNum()-it2.next().getInNum());		
//		}
   for(int i=0;i<alist1.size();i++){
	String suns=alist1.get(i)+"."+alist2.get(i)+"."+alist3.get(i)+"."+alist5.get(i);
	alist4.add(suns);
  }
		this.states = alist4;
		//Set<PurchaseOrderDetail>  purchaseOrderDetails=purchaseOrder.getDetails();
//		//states=purchaseOrderDetails;
//		System.out.println(purchaseOrderDetails.size());
//		for(PurchaseOrderDetail detail:purchaseOrderDetails){
//			System.out.println(detail.getProducName());
//			states.add(detail);
//		}
//		
		return SUCCESS;
	}
	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}

	
	
	public void setFlow(String flow) {
		this.flow = flow;
	}

	public String getFlow() {
		return flow;
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}

	public CodeInvoice getCodeInvoice() {
		return codeInvoice;
	}

	public void setCodeInvoice(CodeInvoice codeInvoice) {
		this.codeInvoice = codeInvoice;
	}

	public CodeInvoiceService getCodeInvoiceService() {
		return codeInvoiceService;
	}

	public void setCodeInvoiceService(CodeInvoiceService codeInvoiceService) {
		this.codeInvoiceService = codeInvoiceService;
	}

	public Code getCode() {
		return code;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public Collection<CodeInvoice> getCodelist() {
		return codelist;
	}

	public void setCodelist(Collection<CodeInvoice> codelist) {
		this.codelist = codelist;
	}
	
}
